import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpService {
    private DatagramSocket socket = null;

    public UdpService(int port) throws SocketException {
        socket = new DatagramSocket(9090);
        //参数是服务器绑定的端口
    }

    public void start() throws IOException {
        System.out.println("服务器开始运行");
        while (true) {
            //服务器需要反复的执行客户的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d],服务器响应:%s,客户机请求:%s", requestPacket.getAddress(),requestPacket.getPort(),
                    response, request);
        }
    }

    public String process(String request) {
        return request;
        //回显服务器，返回请求，不做其他操作
    }

    public static void main(String[] args) throws IOException {
        UdpService service=new UdpService(9090);
        service.start();

    }
}

